package com.htn.common.security.service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.htn.common.core.constant.SecurityConstants;
import com.htn.common.core.utils.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.htn.common.core.constant.CacheConstants;
import com.htn.common.core.constant.Constants;
import com.htn.common.core.utils.ip.IpUtils;
import com.htn.common.redis.service.RedisService;
import com.htn.system.api.model.LoginUser;

/**
 * token验证处理
 * 
 * @author htn
 */
@Component
public class TokenService
{
    @Autowired
    private RedisService redisService;

    private final static long EXPIRE_TIME = Constants.TOKEN_EXPIRE * 60;

    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;

    protected static final long MILLIS_SECOND = 1000;

    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(LoginUser loginUser) {

        String key = ACCESS_TOKEN + loginUser.getUserId();
        if(redisService.hasKey(key)){
            redisService.deleteObject(key);
        }
        // 保存或更新用户token
        Map<String, Object> map = new HashMap<String, Object>();

        // 生成token
        String tokens = JwtTokenUtils.createToken(JSONObject.toJSONString(loginUser), loginUser.getUserId(), true);
        loginUser.setToken(tokens);
        loginUser.setUserId(loginUser.getUserId());
        loginUser.setUsername(loginUser.getUsername());
        loginUser.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));

        map.put(SecurityConstants.TOKEN_HEADER, tokens);
        map.put("phone", loginUser.getUsername());
        redisService.setCacheObject(ACCESS_TOKEN + loginUser.getUserId(), loginUser, EXPIRE_TIME, TimeUnit.DAYS);

        return map;

    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(){
        return getLoginUser(ServletUtils.getRequest());
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request){
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        return getLoginUser(token);
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(String token){
        if (StringUtils.isNotEmpty(token))
        {
            String userKey = getTokenKey(token);
            LoginUser user = redisService.getCacheObject(userKey);
            return user;
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser){
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken()))
        {
            refreshToken(loginUser);
        }
    }

    public void delLoginUser(String token){
        if (StringUtils.isNotEmpty(token))
        {
            String userKey = getTokenKey(token);
            redisService.deleteObject(userKey);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser){
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + EXPIRE_TIME * MILLIS_SECOND);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, EXPIRE_TIME, TimeUnit.SECONDS);
    }

    private String getTokenKey(String token){
        return ACCESS_TOKEN + JwtTokenUtils.getId(token);
    }
}